/**
 * Created by MD-3 on 2017/5/25.
 */

//输入提示
function schAddrEnter() {
    console.log("@log-schAddrEnter");
    var e = window.event || arguments.callee.caller.arguments[0];         //火狐识别不了event
    if (e && e.keyCode == "13") {         //keyCode=13是回车键
        schAddr();
    }
}

function schAddr(){
    var keyword = document.getElementById("keyword").value;
    console.log("@log-schAddr-keyword:"+keyword);

    if(!keyword){   return;}
    var flag = searchDevice(keyword);
    if(!flag){
        searchGeocoder(keyword);
    }
}

function searchGeocoder(keyword) {
    AMap.service(["AMap.Geocoder"], function() {
        var geocoder = new AMap.Geocoder({
            //city: "010", //城市，默认：“全国”
            radius: 1000 //范围，默认：500
        });
        //地理编码,返回地理编码结果
        geocoder.getLocation(keyword, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                geocoder_CallBack(result);
            }
        });
    });
}

//地理编码返回结果展示
function geocoder_CallBack(data) {
    var resultStr = "";
    //地理编码结果数组
    var geocode = data.geocodes;
    var position;
    for (var i in geocode) {
        //拼接输出
        position = geocode[i].location;
        console.log("@log-geocoder_CallBack:"+"<地址>：" + geocode[i].formattedAddress + "----" + "<坐标>：" + geocode[i].location.getLng() + ", " + geocode[i].location.getLat() + "----" + "<匹配级别>：" + geocode[i].level)
    }
    map.panTo(position);
    //map.setFitView();            //根据地图上添加的覆盖物分布情况，自动缩放地图到合适的视野级别
}

function searchDevice(keyword) {
    if (!keyword || ""==keyword) {
        return false;
    }

    var device;
    $.each(deviceMarkerList, function (idx, dev) {
        if (keyword == dev.name || keyword == dev.id ) {
            device = dev;
            return true;
        }
        $.each(dev.childDevlist, function (jdx, childDev) {
            if (keyword == childDev.name || keyword == childDev.id ) {
                device = childDev;
                return true;
            }
        });
    });

    if(device && device.marker){
        var position = device.marker.getPosition();
        map.panTo(position);
        openDeviceInfo(device.id);                      //展开信息窗口
        return true;
    }
    return false;
}